<template>
  <!-- 大屏布局 -->
  <lsd-layout v-if="pageConfig.layout">
    <!-- 大屏布局容器 -->
    <template v-for="container in pageConfig.layout.containerList" :key="container.key">
      <!-- 三级组件（详情）布局容器 -->
      <template v-if="container.type === 'detail'">
        <Transition :name="container.transitionType">
          <lsd-layout-container
            v-if="currentDetailConfig[container.key] && currentDetailConfig[container.key].component"
            :key="container.key"
            :id="container.key"
            :ref="container.key"
            :data-title="container.title"
            :ratio="[currentDetailConfig[container.key].ratioW, currentDetailConfig[container.key].ratioH]"
            :direction="container.direction"
            :height="getDomProp(container.height)"
            :width="getDomProp(container.width)"
            :top="getDomProp(container.top)"
            :right="getDomProp(container.right)"
            :bottom="getDomProp(container.bottom)"
            :left="getDomProp(container.left)"
            :style="currentDetailConfig[container.key].styles || container.styles"
          >
            <async-load-component
              :component="currentDetailConfig[container.key].component"
              :key="currentDetailConfig[container.key].component"
              :config="currentDetailConfig[container.key]"
              :data="currentDetailConfig[container.key].data"
              :transitionType="container.transitionType"
              v-bind="currentDetailConfig[container.key].componentProps || {}"
              @close="closeDetail(container)"
            />
          </lsd-layout-container>
        </Transition>
      </template>

      <!-- 一级、二级组件容器 -->
      <lsd-layout-container
        v-else
        :id="container.key"
        :ref="container.key"
        :data-title="container.title"
        :ratio="[container.ratioW, container.ratioH]"
        :direction="container.direction"
        :height="getDomProp(container.height)"
        :width="getDomProp(container.width)"
        :top="getDomProp(container.top)"
        :right="getDomProp(container.right)"
        :bottom="getDomProp(container.bottom)"
        :left="getDomProp(container.left)"
        :style="container.styles"
      >
        <!-- 二级组件容器 （子路由视图） -->
        <router-view
          v-if="container.type && container.type.includes('second')"
          :spanNum="container.spanNum || pageConfig.layout.spanNumm"
          :transitionType="container.transitionType"
          @setDetail="setDetail"
        ></router-view>

        <!-- 一级组件 -->
        <template v-else>
          <!-- 大屏布局子容器 -->
          <lsd-layout-child-container
            v-for="child in container.children"
            :key="child.key"
            :span="child.span"
            :spanNum="container.spanNum || pageConfig.layout.spanNumm"
            :style="child.styles"
          >
            <!-- 业务组件 -->
            <async-load-component
              v-if="child.component"
              :class="{
                active: currentRouteName === child.key,
                'is-menu': child.hasChildRoute
              }"
              :component="child.component"
              :key="child.component"
              :routeName="child.key"
              :config="child"
              :transitionType="container.transitionType"
              v-bind="child.componentProps || {}"
              @handle="routeName => handle(routeName, child)"
              @setDetail="setDetail"
              @close="closeDetail"
            />
          </lsd-layout-child-container>
        </template>
      </lsd-layout-container>
    </template>

    <!-- 底部内容 -->
    <template #main>
      <!-- 地图 -->
      <!-- <async-load-component class="map-box" component="map" :pageMapConfig="pageConfig.layout.pageMapConfig" /> -->
    </template>
  </lsd-layout>
</template>

<script setup>
/**
 * 母版
 * @author 朱琦
 * @date   时间：2023/2/10
 */
import { ref, onMounted, watch, computed, markRaw, shallowRef, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { getDomProp } from '@/components/layout/utils'
import AsyncLoadComponent from 'motherSet/components/async-load-component'

const route = useRoute()
const router = useRouter()
const store = useStore()

const { proxy } = getCurrentInstance()

// 当前菜单组件的路由名
const currentRouteName = ref(null)
// 是否有二级组件
const hasSecond = ref(false)
// 是否有详情组件
const hasDetail = ref(false)

// 当前详情相关配置
const currentDetailConfig = ref({
  map: null,
  panel: null
})

// 页面配置
const pageConfig = computed(() => store.getters['config/pageConfig'])
// 详情配置
const detailConfig = computed(() => store.getters['config/detailConfig'])

// 监听路由名
watch(
  () => route.params.routeName,
  val => {
    // 清空详情配置
    setDetailConfig()
    // 获取菜单配置
    getMenuConfig(pageConfig.value.layout)
  }
)
// 监听详情配置
watch(
  detailConfig,
  ({ type, actions, data, config }) => {
    setDetailConfig(config, data)
  },
  {
    deep: true
  }
)

onMounted(() => {
  getData()
})

/**
 * 获取页面配置数据
 */
const getData = () => {
  const config = pageConfig.value
  currentRouteName.value = route.params.routeName
  // 当前页面是否有二级组件（是就代表有子路由）
  hasSecond.value = config.type.includes('second')
  // 获取当前菜单组件配置
  hasSecond.value && getMenuConfig(config.layout)

  // 保存 页面配置
  store.commit('config/SET_PAGE_CONFIG', config)
}

/**
 * 获取菜单组件配置
 * @param {Object} layout 布局配置
 */
const getMenuConfig = layout => {
  let currentChildConfig = null
  // 遍历布局容器列表，查找菜单组件
  layout.containerList.some(container => {
    // 遍历子容器列表
    return (
      container.children &&
      container.children.some(child => {
        // 判断有路由名，子模块列表配置的
        if (child.hasChildRoute && child.children && child.children.length) {
          // 没有路由名时，默认展示第一个菜单组件子模块
          currentChildConfig || (currentChildConfig = child)
          // 当前路由名存在时
          if (currentRouteName.value) {
            // 判断是否 与key 相等
            if (currentRouteName.value === child.key) {
              currentChildConfig = child
              return true
            }
            return false
          }
          return true
        }
      })
    )
  })
  // 保存 当前子页面配置
  store.commit('config/SET_PAGE_CHILD_CONFIG', currentChildConfig)

  // 当前没有路由名时，但有子路由配置时，默认跳转该配置子路由
  if (!currentRouteName.value && currentChildConfig) {
    setRoute(currentChildConfig.key)
  }
}

/**
 * 业务组件点击回调-菜单组件
 * @param {String} routeName 路由名
 * @param {Object} config 组件配置
 */
const handle = (routeName, config) => {
  // 组件配置有子路由  且 当前为有菜单组件时
  if (config.hasChildRoute && hasSecond.value) {
    routeName !== currentRouteName.value && setRoute(routeName)
  }
}

/**
 * 设置路由
 * @param {String} routeName 路由名
 */
const setRoute = routeName => {
  currentRouteName.value = routeName
  router.replace({
    name: 'mother-set-child',
    params: {
      routeName: routeName,
      pageId: route.params.pageId
    },
    query: route.params.query
  })
}

/**
 * 详情组件关闭回调
 * @param {*} config
 */
const closeDetail = config => {
  currentDetailConfig.value[config.type] = null
  store.commit('config/SET_DETAIL_CONFIG', {})
}

/**
 * 组件点击设置详情回调
 * @param {Object} data
 */
const setDetail = data => {
  store.commit('config/SET_DETAIL_CONFIG', data)
}

/**
 * 设置当前展示详情配置
 * @param {Array} config 配置
 * @param {Object} data 数据
 */
const setDetailConfig = (config, data) => {
  // 是否有配置
  const hasConfig = config && config.length
  // const detail = {}
  if (hasConfig) {
    // 获取对应配置
    config.forEach(item => {
      item.containerType && (currentDetailConfig.value[item.containerType] = { ...item, data })
    })
  } else {
    // 清空当前详情配置
    currentDetailConfig.value = {}
  }

  // 设置详情配置
  // Object.keys(currentDetailConfig.value).forEach(key => {
  //   currentDetailConfig.value[key] = hasConfig ? detail[key] : null
  // })
}
</script>

<style scoped lang="less">
.lsd-layout {
  .is-menu {
    cursor: pointer;
  }
}
</style>
